import { defineConfig, ConfigEnv, loadEnv } from 'vite';
import viteCompression from 'vite-plugin-compression';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

const pathResolve = (dir: string): any => {
	return resolve(__dirname, '.', dir);
};

const alias: Record<string, string> = {
	'@': pathResolve('src'),
};
const extensions = ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json'];
const viteConfig = defineConfig((mode: ConfigEnv) => {
	const env = loadEnv(mode.mode, process.cwd());
	// 生成代理配置对象
	console.log(env.VITE_OPEN);
	return {
		plugins: [
			vue(),
			viteCompression({
				// 是否在控制台中输出压缩结果
				verbose: true,
				disable: false,
				// 如果体积大于阈值，将被压缩，单位为b，体积过小时请不要压缩，以免适得其反
				threshold: 10240,
				// 压缩算法，可选['gzip'，' brotliccompress '，'deflate '，'deflateRaw']
				algorithm: 'gzip',
				ext: '.gz',
				// 源文件压缩后是否删除(我为了看压缩后的效果，先选择了true)
				deleteOriginFile: true,
			}),
		],
		root: process.cwd(),
		resolve: { alias, extensions },
		base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
		hmr: true,
		optimizeDeps: {},
		server: {
			host: '0.0.0.0',
			port: env.VITE_PORT as undefined as number,
			open: env.VITE_OPEN,
		},
		build: {
			minify: 'terser',
			outDir: 'dist',
			sourcemap: false,
			chunkSizeWarningLimit: 1500,
			terserOptions: {
				compress: {
					drop_console: true,
					drop_debugger: true,
				},
			},
			rollupOptions: {
				output: {
					chunkFileNames: `static/js/[name]-[hash].${new Date().getTime()}.js`,
					entryFileNames: `static/js/[name]-[hash].${new Date().getTime()}.js`,
					assetFileNames: `static/[ext]/[name]-[hash].${new Date().getTime()}.[ext]`,
					compact: true,
					manualChunks(id) {
						if (id.includes('node_modules')) {
							return id.toString().split('node_modules/')[1].split('/')[0].toString();
						}
					},
				},
			},
		},
		css: {
			preprocessorOptions: {
				scss: {
					// additionalData: `@use "@/styles/element/index.scss" as *;`,
				},
			},
		},
	};
});
export default viteConfig;
